#!/bin/bash

_ocos_completions()
{
	local result
	local n=${#COMP_WORDS[@]}
	n=$((n-1))

	if [ "$n" == 1 ]; then
		result="$(</usr/lib/opencloudos-tools/ocos-comp.txt)"
	elif [ "$n" -gt 1 -a "${COMP_WORDS[1]}" == ops ]; then
		local cmd=(ocos "${COMP_WORDS[@]}")
		cmd[1]=ops
		cmd[2]="--bashcomp"
		unset cmd[$((n+1))]
		result="$(${cmd[@]} </dev/null 2>/dev/null)"
		local lead="${result%% *}"
		if [ -z "${lead##*:*}" -o -z "${result##*$'\n' *}" -o -z "${result##*$'\t'*}" ]; then
			result=
		fi
	elif [ "$n" == "2" ]; then
		local cmd="${COMP_WORDS[1]}"
		local cur="${COMP_WORDS[2]}"
		local list=
		if [ "$cmd" == "backup" ]; then
			COMPREPLY=($(compgen -W "reboot" -- $cur))
			return
		elif [ "$cmd" == "install" ]; then
			list=available
		elif [ "$cmd" == "update" ]; then
			list=updates
		elif [ "$cmd" == "check" ]; then
			list=installed
		else
			return
		fi
		if [[ "$cur" == @(*/|[.~])*  ]]; then
		    [ "$(type -t _filedir)" = "function" ] && _filedir rpm;
		else
		    [ "$(type -t _yum_list)" = "function" ] && _yum_list $list
		fi
		return
	fi
	if [ -n ".$result" ]; then
		local IFS=$'\n'
		local sug=($(compgen -W "$result" -- ${COMP_WORDS[$n]}))
		if [ "${#sug[@]}" == "1" ]; then
			local number="${sug[0]/%\ */}"
			COMPREPLY=("$number")
		else
			for i in "${!sug[@]}"; do
				sug[$i]="$(printf '%*s' "-$COLUMNS"  "${sug[$i]}")"
			done

			COMPREPLY=("${sug[@]}")
		fi
	fi
}
complete -F _ocos_completions ocos oc
